package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class MinioUtil {

    private String host;
    private String url;
    private String accessKey;
    private String secretKey;
    private String bucket;

    /**
     * 文件上传
     *
     * @return
     */
    public String upload(MultipartFile multipartFile) throws Exception{
        MinioClient minioClient=null;
        try {
            minioClient=new MinioClient(this.host, this.accessKey, this.secretKey);
            log.info("成功构建minioClinet");
        }catch (Exception e){
            log.info("创建minioClient失败，{}",e.getMessage());
        }
        // bucket 不存在，创建
        if (!minioClient.bucketExists(this.bucket)) {
            minioClient.makeBucket(this.bucket);
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {
            // 上传文件的名称
            String fileName = multipartFile.getOriginalFilename();
            UUID uuid = UUID.randomUUID();
            String photoSuffix = fileName.substring(fileName.lastIndexOf('.'));
            String photoName = uuid.toString() + photoSuffix;
            // PutObjectOptions，上传配置(文件大小，内存中文件分片大小)
            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
            // 文件的ContentType
            putObjectOptions.setContentType(multipartFile.getContentType());
            //将文件上传到minio
            minioClient.putObject(this.bucket, photoName, inputStream, putObjectOptions);
            // 返回访问路径
            return this.url+"/"+ UriUtils.encode(photoName, StandardCharsets.UTF_8);
        }
    }
}
